<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="实现Raft协议：Part 2 - 指令和日志复制, 码道诚公">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="baidu-site-verification" content="code-oqVlgh2wQV" />
    <meta name="google-site-verification" content="Z-8Fm46WY6NL_3kxilmoqToW4jnvyF7boTgciTLBXUs" />
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>实现Raft协议：Part 2 - 指令和日志复制 | 码道诚公</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.2.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="码道诚公" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">码道诚公</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">码道诚公</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/8.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">实现Raft协议：Part 2 - 指令和日志复制</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E4%B8%80%E8%87%B4%E6%80%A7/">
                                <span class="chip bg-color">分布式一致性</span>
                            </a>
                        
                            <a href="/tags/Raft/">
                                <span class="chip bg-color">Raft</span>
                            </a>
                        
                            <a href="/tags/%E8%AF%91%E6%96%87/">
                                <span class="chip bg-color">译文</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F/" class="post-category">
                                分布式
                            </a>
                        
                            <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F/%E4%B8%80%E8%87%B4%E6%80%A7%E5%8D%8F%E8%AE%AE/" class="post-category">
                                一致性协议
                            </a>
                        
                            <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F/%E4%B8%80%E8%87%B4%E6%80%A7%E5%8D%8F%E8%AE%AE/Raft/" class="post-category">
                                Raft
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-03-04
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    5.9k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    22 分
                </div>
                

                
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>翻译自<a target="_blank" rel="noopener" href="https://eli.thegreenplace.net/archives/all">Eli Bendersky</a>的<a target="_blank" rel="noopener" href="https://eli.thegreenplace.net/2020/implementing-raft-part-2-commands-and-log-replication/">系列博客</a>，已获得原作者授权。</p>
<p>本文是系列文章中的第一部分，本系列文章旨在介绍Raft分布式一致性协议及其Go语言实现。文章的完整列表如下：</p>
<ul>
<li>序言：<a href="/posts/772d24e8.html" title="介绍">介绍</a></li>
<li>第一部分：<a href="/posts/be586517.html" title="选主">选主</a></li>
<li>第二部分：指令和日志复制(本文)</li>
<li>第三部分：<a href="/posts/9e1d4cec.html" title="持久性和优化">持久性和优化</a></li>
</ul>
<p>在这一部分，我们会大幅强化Raft的实现，做到能够实际处理客户端提交的指令，并在Raft集群中复制它们。代码结构与<a href="/posts/be586517.html" title="第一部分">第一部分</a>相同，会有一些新的结构体和函数定义，对旧代码也会有一些改动——我会对这些做简短的解释。</p>
<p>本部分的所有代码都在<a target="_blank" rel="noopener" href="https://github.com/eliben/raft/tree/master/part2">这个目录</a>。</p>
<h3 id="客户端交互"><a href="#客户端交互" class="headerlink" title="客户端交互"></a>客户端交互</h3><p>我们在<a href="/posts/772d24e8.html" title="序言">序言</a>中对客户端交互进行了简短的讨论，我强烈建议您返回去重新读一下对应章节。接下来，我们不会关注客户端<em>如何</em>找到领导者，相反，我们讨论的是当他<em>已经找到</em>领导者时，会发生什么。</p>
<p>首先说明一下术语。如前所述，客户端使用Raft协议来复制一系列的<em>指令</em>，这些指令可以视为通用状态机的输入。就我们的Raft实现而言，这些指令可以是完全任意的，我们使用Go中的空指针类型（interface{}）来进行表示。在Raft的一致性历程中，一条指令会经历以下步骤：</p>
<ol>
<li>首先，指令被客户端<strong>呈递（submit）</strong>给领导者，在一个Raft集群中，一条指令通常只会呈递给一个服务器。</li>
<li>领导者将指令<strong>复制（replicates）</strong>给其追随者。</li>
<li>最后，一旦领导者确认日志已经被充分复制（也就是说，集群中的多数服务器已经确认指令保存在其日志中<sup id="fnref:1"><a href="#fn:1" rel="footnote">1</a></sup>），指令会被<strong>提交（commit）</strong>，并且将新提交通知给所有的客户端。</li>
</ol>
<p>注意在呈递和提交指令之间的不对称性——在检查我们即将讨论的实现策略时，牢记这一点很重要。一条指令会呈递给单个Raft服务器，但是一段时候后多个服务器（特别是已连接/活动的同伴服务器）都会提交这个指令并通知各自的客户端。</p>
<p>回顾一下序言中的示意图：</p>
<p><img src="/posts/25bc8c4b/raft-consensus-module-log.png" alt="Raft consensus module and log connected to state machine"></p>
<p>状态机代表使用Raft协议进行复制的任意服务，如键值数据库。**<em>已提交**</em>的指令会改变服务的状态（如：在数据库中新增一个键值对）。</p>
<p>当我们在<code>Raft ConsensusModule</code>上下文中讨论<em>客户端</em>时，通常指的是（上面说的）服务，因为这也是**<em>提交**</em>所通知的对象。换句话说，上图中的一致性模块指向服务状态机的黑色箭头就是这里所说的通知。</p>
<p>客户端还有另外的含义，就是该服务的客户端（比如键值数据库的用户）。服务与其客户端之间的交互是服务自身的业务，在本文中，我们只关注Raft与服务之间的交互。</p>
<blockquote>
<p><strong>译者注：</strong>作者在这里对于指令的阶段分别使用了submit和commit进行描述，在通常的翻译中，这两个词都表示<strong>提交</strong>。我个人理解，<code>submit</code>表示提交时，倾向于对象A向对象B提交某些内容，而<code>commit</code>表示提交时，倾向于本地记录的确认。为了避免歧义，这里将<code>submit</code>翻译为<code>呈递</code>，表示服务向Raft一致性模块发送了指令；<code>commit</code>仍译为<code>提交</code>，表示Raft一致性模块确认本地的指令记录。在这里特别解释一下，如有更好的建议，可以联系我进行修改。</p>
</blockquote>
<h3 id="实现：提交通道"><a href="#实现：提交通道" class="headerlink" title="实现：提交通道"></a>实现：提交通道</h3><p>在我们的实现中，在新建<code>ConsensusModule</code>时会接收一个<code>commit channel</code>作为参数——CM可以使用该通道向调用方发送已提交的指令：<code>commitChan chan&lt;- CommitEntry</code>。</p>
<p><code>CommitEntry</code>定义如下：</p>
<pre class=" language-go"><code class="language-go"><span class="token comment" spellcheck="true">/*
    CommitEntry就是Raft向提交通道发送的数据。每一条提交的条目都会通知客户端，
    表明指令已满足一致性，可以应用到客户端的状态机上。
*/</span>
<span class="token keyword">type</span> CommitEntry <span class="token keyword">struct</span> <span class="token punctuation">{</span>
  <span class="token comment" spellcheck="true">// Command 是被提交的客户端指令</span>
  Command <span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span>

  <span class="token comment" spellcheck="true">// Index 是被提交的客户端指令对应的日志索引</span>
  Index <span class="token builtin">int</span>

  <span class="token comment" spellcheck="true">// Term 是被提交的客户端指令对应的任期</span>
  Term <span class="token builtin">int</span>
<span class="token punctuation">}</span></code></pre>
<p>使用channel是一种设计选择，但是这不是唯一的解决方法。我们也可以改用回调；在创建<code>ConsensusModule</code>时调用方会注册一个回调函数，一旦我们需要提交指令，就可以执行这个回调函数。</p>
<p>我们很快会看到通过channel发送日志条目的代码，在此之前，我们必须讨论Raft服务器如何复制命令并决定是否提交。</p>
<h3 id="Raft日志"><a href="#Raft日志" class="headerlink" title="Raft日志"></a>Raft日志</h3><p>在这个系列中，Raft日志已经被提及很多次了，但是我们还没有对此进行过多的介绍。日志就是要应用于状态机的指令的线性序列，如果需要的话，日志要能够从某个起始状态开始”重放“状态机。正常运行时，所有Raft同伴的日志的相同的。当领导者收到新指令时，会先加入自己的日志中，然后将其复制给所有的追随者。追随者将命令放在日志中并向领导者确认，后者会记录已安全复制到集群中多数服务器的最新日志索引。</p>
<p>Raft论文中有一些日志的示意图，类似：</p>
<p><img src="/posts/25bc8c4b/logdiagram.png" alt="Raft log with terms and indexes"></p>
<p>每个方格是一条日志条目。方格顶部的数字是该 条目添加到日志时的任期（也就是第一部分所说的任期）；方格底部是日志条目包含的键-值指令。每个日志条目都有一个线性索引<sup id="fnref:2"><a href="#fn:2" rel="footnote">2</a></sup>，方格的颜色用另一种方式体现了任期。</p>
<p>如果上面的日志应用到一个空的键-值存储中，最终的结果就是<code>x = 4, y = 7</code>。</p>
<p>在我们的实现中，日志条目的结构如下：</p>
<pre class=" language-go"><code class="language-go"><span class="token keyword">type</span> LogEntry <span class="token keyword">struct</span> <span class="token punctuation">{</span>
  Command <span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span>
  Term    <span class="token builtin">int</span>
<span class="token punctuation">}</span></code></pre>
<p>每个<code>ConsensusModule</code>的日志属性就是数组<code>log []LogEntry</code>。客户端通常不在乎任期，但是，任期对于Raft的正确性至关重要，因此在阅读代码时请务必牢记。</p>
<h3 id="呈递新指令"><a href="#呈递新指令" class="headerlink" title="呈递新指令"></a>呈递新指令</h3><p>我们首先看一下新加的方法<code>Submit</code>，客户端通过该方法呈递新指令：</p>
<pre class=" language-go"><code class="language-go"><span class="token comment" spellcheck="true">/*
    Submit方法会向CM呈递一条新的指令。这个函数是非阻塞的;
    客户端读取构造函数中传入的commit channel，以获得新提交条目的通知。
    如果当前CM是领导者返回true——表示指令被接受了。
    如果返回false，客户端会寻找新的服务器呈递该指令。
*/</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>cm <span class="token operator">*</span>ConsensusModule<span class="token punctuation">)</span> <span class="token function">Submit</span><span class="token punctuation">(</span>command <span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token builtin">bool</span> <span class="token punctuation">{</span>
  cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  <span class="token keyword">defer</span> cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

  cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"Submit received by %v: %v"</span><span class="token punctuation">,</span> cm<span class="token punctuation">.</span>state<span class="token punctuation">,</span> command<span class="token punctuation">)</span>
  <span class="token keyword">if</span> cm<span class="token punctuation">.</span>state <span class="token operator">==</span> Leader <span class="token punctuation">{</span>
    cm<span class="token punctuation">.</span>log <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>cm<span class="token punctuation">.</span>log<span class="token punctuation">,</span> LogEntry<span class="token punctuation">{</span>Command<span class="token punctuation">:</span> command<span class="token punctuation">,</span> Term<span class="token punctuation">:</span> cm<span class="token punctuation">.</span>currentTerm<span class="token punctuation">}</span><span class="token punctuation">)</span>
    cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"... log=%v"</span><span class="token punctuation">,</span> cm<span class="token punctuation">.</span>log<span class="token punctuation">)</span>
    <span class="token keyword">return</span> <span class="token boolean">true</span>
  <span class="token punctuation">}</span>
  <span class="token keyword">return</span> <span class="token boolean">false</span>
<span class="token punctuation">}</span></code></pre>
<p>逻辑很简单，如果CM是领导者，则将新指令添加到日志中，并返回<code>true</code>。否则，忽略请求并返回<code>false</code>。</p>
<p><strong>Q：</strong><code>Submit</code>方法返<code>true</code>是否足以表明客户端已经将指令呈递到领导者？    </p>
<p><strong>A：</strong>很遗憾并不是。在极少数情况下，领导者可能会与其它Raft服务器之间出现网络分区，而其它服务器很快会重新选举新的领导者，但是客户端可能仍然连接在旧的领导者。客户端对于其呈递的指令应该等待一段合理的时间，检查该指令是否出现在commit channel中；如果没有的话，就表明它连接的是错误的领导者，应该连接其它领导者进行重试。</p>
<h3 id="复制日志条目"><a href="#复制日志条目" class="headerlink" title="复制日志条目"></a>复制日志条目</h3><p>我们刚刚看到呈递给领导者的指令被追加到了日志的末尾，但是这条新指令如何传给追随者呢？领导者的执行步骤在Raft论文的<code>Figure 2</code>中的<code>服务器规则</code>部分有详细描述（可以返回第一部分的附言查看详细内容）。我们在<code>leaderSendHeartbeats</code>方法中完成该逻辑，这是一个新方法<sup id="fnref:3"><a href="#fn:3" rel="footnote">3</a></sup>：</p>
<pre class=" language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token punctuation">(</span>cm <span class="token operator">*</span>ConsensusModule<span class="token punctuation">)</span> <span class="token function">leaderSendHeartbeats</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  savedCurrentTerm <span class="token operator">:=</span> cm<span class="token punctuation">.</span>currentTerm
  cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

  <span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> peerId <span class="token operator">:=</span> <span class="token keyword">range</span> cm<span class="token punctuation">.</span>peerIds <span class="token punctuation">{</span>
    <span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span>peerId <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      ni <span class="token operator">:=</span> cm<span class="token punctuation">.</span>nextIndex<span class="token punctuation">[</span>peerId<span class="token punctuation">]</span>
      prevLogIndex <span class="token operator">:=</span> ni <span class="token operator">-</span> <span class="token number">1</span>
      prevLogTerm <span class="token operator">:=</span> <span class="token operator">-</span><span class="token number">1</span>
      <span class="token keyword">if</span> prevLogIndex <span class="token operator">>=</span> <span class="token number">0</span> <span class="token punctuation">{</span>
        prevLogTerm <span class="token operator">=</span> cm<span class="token punctuation">.</span>log<span class="token punctuation">[</span>prevLogIndex<span class="token punctuation">]</span><span class="token punctuation">.</span>Term
      <span class="token punctuation">}</span>
      entries <span class="token operator">:=</span> cm<span class="token punctuation">.</span>log<span class="token punctuation">[</span>ni<span class="token punctuation">:</span><span class="token punctuation">]</span>

      args <span class="token operator">:=</span> AppendEntriesArgs<span class="token punctuation">{</span>
        Term<span class="token punctuation">:</span>         savedCurrentTerm<span class="token punctuation">,</span>
        LeaderId<span class="token punctuation">:</span>     cm<span class="token punctuation">.</span>id<span class="token punctuation">,</span>
        PrevLogIndex<span class="token punctuation">:</span> prevLogIndex<span class="token punctuation">,</span>
        PrevLogTerm<span class="token punctuation">:</span>  prevLogTerm<span class="token punctuation">,</span>
        Entries<span class="token punctuation">:</span>      entries<span class="token punctuation">,</span>
        LeaderCommit<span class="token punctuation">:</span> cm<span class="token punctuation">.</span>commitIndex<span class="token punctuation">,</span>
      <span class="token punctuation">}</span>
      cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"sending AppendEntries to %v: ni=%d, args=%+v"</span><span class="token punctuation">,</span> peerId<span class="token punctuation">,</span> ni<span class="token punctuation">,</span> args<span class="token punctuation">)</span>
      <span class="token keyword">var</span> reply AppendEntriesReply
      <span class="token keyword">if</span> err <span class="token operator">:=</span> cm<span class="token punctuation">.</span>server<span class="token punctuation">.</span><span class="token function">Call</span><span class="token punctuation">(</span>peerId<span class="token punctuation">,</span> <span class="token string">"ConsensusModule.AppendEntries"</span><span class="token punctuation">,</span> args<span class="token punctuation">,</span> <span class="token operator">&amp;</span>reply<span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
        cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token keyword">defer</span> cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token keyword">if</span> reply<span class="token punctuation">.</span>Term <span class="token operator">></span> savedCurrentTerm <span class="token punctuation">{</span>
          cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"term out of date in heartbeat reply"</span><span class="token punctuation">)</span>
          cm<span class="token punctuation">.</span><span class="token function">becomeFollower</span><span class="token punctuation">(</span>reply<span class="token punctuation">.</span>Term<span class="token punctuation">)</span>
          <span class="token keyword">return</span>
        <span class="token punctuation">}</span>

        <span class="token keyword">if</span> cm<span class="token punctuation">.</span>state <span class="token operator">==</span> Leader <span class="token operator">&amp;&amp;</span> savedCurrentTerm <span class="token operator">==</span> reply<span class="token punctuation">.</span>Term <span class="token punctuation">{</span>
          <span class="token keyword">if</span> reply<span class="token punctuation">.</span>Success <span class="token punctuation">{</span>
            cm<span class="token punctuation">.</span>nextIndex<span class="token punctuation">[</span>peerId<span class="token punctuation">]</span> <span class="token operator">=</span> ni <span class="token operator">+</span> <span class="token function">len</span><span class="token punctuation">(</span>entries<span class="token punctuation">)</span>
            cm<span class="token punctuation">.</span>matchIndex<span class="token punctuation">[</span>peerId<span class="token punctuation">]</span> <span class="token operator">=</span> cm<span class="token punctuation">.</span>nextIndex<span class="token punctuation">[</span>peerId<span class="token punctuation">]</span> <span class="token operator">-</span> <span class="token number">1</span>
            cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"AppendEntries reply from %d success: nextIndex := %v, matchIndex := %v"</span><span class="token punctuation">,</span> peerId<span class="token punctuation">,</span> cm<span class="token punctuation">.</span>nextIndex<span class="token punctuation">,</span> cm<span class="token punctuation">.</span>matchIndex<span class="token punctuation">)</span>

            savedCommitIndex <span class="token operator">:=</span> cm<span class="token punctuation">.</span>commitIndex
            <span class="token keyword">for</span> i <span class="token operator">:=</span> cm<span class="token punctuation">.</span>commitIndex <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token function">len</span><span class="token punctuation">(</span>cm<span class="token punctuation">.</span>log<span class="token punctuation">)</span><span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
              <span class="token keyword">if</span> cm<span class="token punctuation">.</span>log<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">.</span>Term <span class="token operator">==</span> cm<span class="token punctuation">.</span>currentTerm <span class="token punctuation">{</span>
                matchCount <span class="token operator">:=</span> <span class="token number">1</span>
                <span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> peerId <span class="token operator">:=</span> <span class="token keyword">range</span> cm<span class="token punctuation">.</span>peerIds <span class="token punctuation">{</span>
                  <span class="token keyword">if</span> cm<span class="token punctuation">.</span>matchIndex<span class="token punctuation">[</span>peerId<span class="token punctuation">]</span> <span class="token operator">>=</span> i <span class="token punctuation">{</span>
                    matchCount<span class="token operator">++</span>
                  <span class="token punctuation">}</span>
                <span class="token punctuation">}</span>
                <span class="token keyword">if</span> matchCount<span class="token operator">*</span><span class="token number">2</span> <span class="token operator">></span> <span class="token function">len</span><span class="token punctuation">(</span>cm<span class="token punctuation">.</span>peerIds<span class="token punctuation">)</span><span class="token operator">+</span><span class="token number">1</span> <span class="token punctuation">{</span>
                  cm<span class="token punctuation">.</span>commitIndex <span class="token operator">=</span> i
                <span class="token punctuation">}</span>
              <span class="token punctuation">}</span>
            <span class="token punctuation">}</span>
            <span class="token keyword">if</span> cm<span class="token punctuation">.</span>commitIndex <span class="token operator">!=</span> savedCommitIndex <span class="token punctuation">{</span>
              cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"leader sets commitIndex := %d"</span><span class="token punctuation">,</span> cm<span class="token punctuation">.</span>commitIndex<span class="token punctuation">)</span>
              cm<span class="token punctuation">.</span>newCommitReadyChan <span class="token operator">&lt;-</span> <span class="token keyword">struct</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">{</span><span class="token punctuation">}</span>
            <span class="token punctuation">}</span>
          <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
            cm<span class="token punctuation">.</span>nextIndex<span class="token punctuation">[</span>peerId<span class="token punctuation">]</span> <span class="token operator">=</span> ni <span class="token operator">-</span> <span class="token number">1</span>
            cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"AppendEntries reply from %d !success: nextIndex := %d"</span><span class="token punctuation">,</span> peerId<span class="token punctuation">,</span> ni<span class="token number">-1</span><span class="token punctuation">)</span>
          <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">(</span>peerId<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p>这确实比第一部分的逻辑复杂得多，但它实际上也就是按照论文的图2所写的。关于这段代码的几点说明：</p>
<ul>
<li>AE请求参数的字段已经全部补齐，可以查阅论文中的图2了解各自的含义</li>
<li>AE的应答中包含一个<code>success</code>字段，用于告知领导者，其请求的追随者是否得到了匹配的<code>prevLogIndex</code>和<code>prevLogTerm</code>。根据该字段，领导者会更新追随者对应的<code>nextIndex</code>。</li>
<li><code>commitIndex</code>是根据已复制某天日志条目的追随者数量来更新的，如果某条索引已复制到集群中的多数服务器，<code>commitIndex</code>就会修改为该索引值。</li>
</ul>
<p>代码的这一部分对于前面讨论发客户端交互非常重要：</p>
<pre class=" language-go"><code class="language-go"><span class="token keyword">if</span> cm<span class="token punctuation">.</span>commitIndex <span class="token operator">!=</span> savedCommitIndex <span class="token punctuation">{</span>
  cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"leader sets commitIndex := %d"</span><span class="token punctuation">,</span> cm<span class="token punctuation">.</span>commitIndex<span class="token punctuation">)</span>
  cm<span class="token punctuation">.</span>newCommitReadyChan <span class="token operator">&lt;-</span> <span class="token keyword">struct</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">{</span><span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p><code>newCommitReadyChan</code>是CM内部使用的一个通道，用来通知在<code>commit channel</code>上有新条目可以发生给客户端。它是通过下面的方法起作用的，CM启动时会在goroutine运行该方法：</p>
<pre class=" language-go"><code class="language-go"><span class="token comment" spellcheck="true">/*
    commitChanSender负责在cm.commitChan上发送已提交的日志条目。
    它会监听newCommitReadyChan的通知并检查哪些条目可以发送（给客户端）。
    该方法应该在单独的后台goroutine中运行；cm.commitChan可能会有缓冲来限制客户端消费已提交指令的速度。
    当newCommitReadyChan关闭时方法结束。
*/</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>cm <span class="token operator">*</span>ConsensusModule<span class="token punctuation">)</span> <span class="token function">commitChanSender</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">for</span> <span class="token keyword">range</span> cm<span class="token punctuation">.</span>newCommitReadyChan <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// 查找需要执行哪些指令</span>
    cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    savedTerm <span class="token operator">:=</span> cm<span class="token punctuation">.</span>currentTerm
    savedLastApplied <span class="token operator">:=</span> cm<span class="token punctuation">.</span>lastApplied
    <span class="token keyword">var</span> entries <span class="token punctuation">[</span><span class="token punctuation">]</span>LogEntry
    <span class="token keyword">if</span> cm<span class="token punctuation">.</span>commitIndex <span class="token operator">></span> cm<span class="token punctuation">.</span>lastApplied <span class="token punctuation">{</span>
      entries <span class="token operator">=</span> cm<span class="token punctuation">.</span>log<span class="token punctuation">[</span>cm<span class="token punctuation">.</span>lastApplied<span class="token operator">+</span><span class="token number">1</span> <span class="token punctuation">:</span> cm<span class="token punctuation">.</span>commitIndex<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">]</span>
      cm<span class="token punctuation">.</span>lastApplied <span class="token operator">=</span> cm<span class="token punctuation">.</span>commitIndex
    <span class="token punctuation">}</span>
    cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"commitChanSender entries=%v, savedLastApplied=%d"</span><span class="token punctuation">,</span> entries<span class="token punctuation">,</span> savedLastApplied<span class="token punctuation">)</span>

    <span class="token keyword">for</span> i<span class="token punctuation">,</span> entry <span class="token operator">:=</span> <span class="token keyword">range</span> entries <span class="token punctuation">{</span>
      cm<span class="token punctuation">.</span>commitChan <span class="token operator">&lt;-</span> CommitEntry<span class="token punctuation">{</span>
        Command<span class="token punctuation">:</span> entry<span class="token punctuation">.</span>Command<span class="token punctuation">,</span>
        Index<span class="token punctuation">:</span>   savedLastApplied <span class="token operator">+</span> i <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">,</span>
        Term<span class="token punctuation">:</span>    savedTerm<span class="token punctuation">,</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
  cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"commitChanSender done"</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span></code></pre>
<p>该方法会更新<code>lastApplied</code>状态变量，以了解哪些条目已发送到客户端，并保证只发送新的条目。</p>
<h3 id="更新追随者的日志"><a href="#更新追随者的日志" class="headerlink" title="更新追随者的日志"></a>更新追随者的日志</h3><p>我们已经讨论过领导者如何处理新日志条目，现在来查看一下追随者的代码，尤其是其中的<code>AppendEntries</code>方法。</p>
<pre class=" language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token punctuation">(</span>cm <span class="token operator">*</span>ConsensusModule<span class="token punctuation">)</span> <span class="token function">AppendEntries</span><span class="token punctuation">(</span>args AppendEntriesArgs<span class="token punctuation">,</span> reply <span class="token operator">*</span>AppendEntriesReply<span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">{</span>
  cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  <span class="token keyword">defer</span> cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  <span class="token keyword">if</span> cm<span class="token punctuation">.</span>state <span class="token operator">==</span> Dead <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token boolean">nil</span>
  <span class="token punctuation">}</span>
  cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"AppendEntries: %+v"</span><span class="token punctuation">,</span> args<span class="token punctuation">)</span>

  <span class="token comment" spellcheck="true">// 请求中的任期大于本地任期，转换为追随者状态</span>
  <span class="token keyword">if</span> args<span class="token punctuation">.</span>Term <span class="token operator">></span> cm<span class="token punctuation">.</span>currentTerm <span class="token punctuation">{</span>
    cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"... term out of date in AppendEntries"</span><span class="token punctuation">)</span>
    cm<span class="token punctuation">.</span><span class="token function">becomeFollower</span><span class="token punctuation">(</span>args<span class="token punctuation">.</span>Term<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>

  reply<span class="token punctuation">.</span>Success <span class="token operator">=</span> <span class="token boolean">false</span>
  <span class="token keyword">if</span> args<span class="token punctuation">.</span>Term <span class="token operator">==</span> cm<span class="token punctuation">.</span>currentTerm <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// 如果当前状态不是追随者，则变为追随者</span>
    <span class="token keyword">if</span> cm<span class="token punctuation">.</span>state <span class="token operator">!=</span> Follower <span class="token punctuation">{</span>
      cm<span class="token punctuation">.</span><span class="token function">becomeFollower</span><span class="token punctuation">(</span>args<span class="token punctuation">.</span>Term<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
    cm<span class="token punctuation">.</span>electionResetEvent <span class="token operator">=</span> time<span class="token punctuation">.</span><span class="token function">Now</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true">// 以下代码为第二部分新增</span>

    <span class="token comment" spellcheck="true">// 检查本地的日志在索引PrevLogIndex处是否包含任期与PrevLogTerm匹配的记录？</span>
    <span class="token comment" spellcheck="true">// 注意在PrevLogIndex=-1的极端情况下，这里应该是true</span>
    <span class="token keyword">if</span> args<span class="token punctuation">.</span>PrevLogIndex <span class="token operator">==</span> <span class="token operator">-</span><span class="token number">1</span> <span class="token operator">||</span>
      <span class="token punctuation">(</span>args<span class="token punctuation">.</span>PrevLogIndex <span class="token operator">&lt;</span> <span class="token function">len</span><span class="token punctuation">(</span>cm<span class="token punctuation">.</span>log<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> args<span class="token punctuation">.</span>PrevLogTerm <span class="token operator">==</span> cm<span class="token punctuation">.</span>log<span class="token punctuation">[</span>args<span class="token punctuation">.</span>PrevLogIndex<span class="token punctuation">]</span><span class="token punctuation">.</span>Term<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      reply<span class="token punctuation">.</span>Success <span class="token operator">=</span> <span class="token boolean">true</span>

      <span class="token comment" spellcheck="true">// 找到插入点 —— 索引从PrevLogIndex+1开始的本地日志与RPC发送的新条目间出现任期不匹配的位置。</span>
      logInsertIndex <span class="token operator">:=</span> args<span class="token punctuation">.</span>PrevLogIndex <span class="token operator">+</span> <span class="token number">1</span>
      newEntriesIndex <span class="token operator">:=</span> <span class="token number">0</span>

      <span class="token keyword">for</span> <span class="token punctuation">{</span>
        <span class="token keyword">if</span> logInsertIndex <span class="token operator">>=</span> <span class="token function">len</span><span class="token punctuation">(</span>cm<span class="token punctuation">.</span>log<span class="token punctuation">)</span> <span class="token operator">||</span> newEntriesIndex <span class="token operator">>=</span> <span class="token function">len</span><span class="token punctuation">(</span>args<span class="token punctuation">.</span>Entries<span class="token punctuation">)</span> <span class="token punctuation">{</span>
          <span class="token keyword">break</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">if</span> cm<span class="token punctuation">.</span>log<span class="token punctuation">[</span>logInsertIndex<span class="token punctuation">]</span><span class="token punctuation">.</span>Term <span class="token operator">!=</span> args<span class="token punctuation">.</span>Entries<span class="token punctuation">[</span>newEntriesIndex<span class="token punctuation">]</span><span class="token punctuation">.</span>Term <span class="token punctuation">{</span>
          <span class="token keyword">break</span>
        <span class="token punctuation">}</span>
        logInsertIndex<span class="token operator">++</span>
        newEntriesIndex<span class="token operator">++</span>
      <span class="token punctuation">}</span>
      <span class="token comment" spellcheck="true">/*
        循环结束时：
        - logInsertIndex指向本地日志结尾，或者是与领导者发送日志间存在任期冲突的索引位置
        - newEntriesIndex指向请求条目的结尾，或者是与本地日志存在任期冲突的索引位置
      */</span>
      <span class="token keyword">if</span> newEntriesIndex <span class="token operator">&lt;</span> <span class="token function">len</span><span class="token punctuation">(</span>args<span class="token punctuation">.</span>Entries<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"... inserting entries %v from index %d"</span><span class="token punctuation">,</span> args<span class="token punctuation">.</span>Entries<span class="token punctuation">[</span>newEntriesIndex<span class="token punctuation">:</span><span class="token punctuation">]</span><span class="token punctuation">,</span> logInsertIndex<span class="token punctuation">)</span>
        cm<span class="token punctuation">.</span>log <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>cm<span class="token punctuation">.</span>log<span class="token punctuation">[</span><span class="token punctuation">:</span>logInsertIndex<span class="token punctuation">]</span><span class="token punctuation">,</span> args<span class="token punctuation">.</span>Entries<span class="token punctuation">[</span>newEntriesIndex<span class="token punctuation">:</span><span class="token punctuation">]</span><span class="token operator">...</span><span class="token punctuation">)</span>
        cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"... log is now: %v"</span><span class="token punctuation">,</span> cm<span class="token punctuation">.</span>log<span class="token punctuation">)</span>
      <span class="token punctuation">}</span>

      <span class="token comment" spellcheck="true">// Set commit index.</span>
      <span class="token keyword">if</span> args<span class="token punctuation">.</span>LeaderCommit <span class="token operator">></span> cm<span class="token punctuation">.</span>commitIndex <span class="token punctuation">{</span>
        cm<span class="token punctuation">.</span>commitIndex <span class="token operator">=</span> <span class="token function">intMin</span><span class="token punctuation">(</span>args<span class="token punctuation">.</span>LeaderCommit<span class="token punctuation">,</span> <span class="token function">len</span><span class="token punctuation">(</span>cm<span class="token punctuation">.</span>log<span class="token punctuation">)</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span>
        cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"... setting commitIndex=%d"</span><span class="token punctuation">,</span> cm<span class="token punctuation">.</span>commitIndex<span class="token punctuation">)</span>
        cm<span class="token punctuation">.</span>newCommitReadyChan <span class="token operator">&lt;-</span> <span class="token keyword">struct</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">{</span><span class="token punctuation">}</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>

  reply<span class="token punctuation">.</span>Term <span class="token operator">=</span> cm<span class="token punctuation">.</span>currentTerm
  cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"AppendEntries reply: %+v"</span><span class="token punctuation">,</span> <span class="token operator">*</span>reply<span class="token punctuation">)</span>
  <span class="token keyword">return</span> <span class="token boolean">nil</span>
<span class="token punctuation">}</span></code></pre>
<p>这段代码严格遵循了论文图2中的算法（AppendEntries的<code>Received implementation</code>部分），而且也给出了很好的注释。</p>
<p>注意代码当中，如果领导者的<code>LeaderCommit</code>大于自身的<code>cm.commitIndex</code>时，会在<code>cm.newCommitReadyChan</code>通道发送数据。这就是追随者从领导者处知道新增的日志条目可以提交的时间。</p>
<p>当领导者在AE请求中发送新的日志条目时，会出现以下情况：</p>
<ul>
<li>追随者将新条目追加到本地日志中，并向领导者回复<code>success=true</code></li>
<li>结果就是，领导者为该追随者更新其对应的<code>matchIndex</code>。当有足够的追随者的<code>matchIndex</code>指向下一索引时，领导者会更新<code>commitIndex</code>并在下一次AE请求中发给所有追随者（在<code>leaderCommit</code>字段中）</li>
<li>当追随者收到新的<code>leaderCommit</code>，它们会意识到有新的日志条目被提交了，它们就会通过commit channel把这些指令发给其客户端。</li>
</ul>
<p><strong>Q：</strong>提交一条新指令需要多少次RPC往返？</p>
<p><strong>A：</strong>2次。第一次请求中，领导者发送下一条日志条目给追随者，追随者进行确认。领导者处理AE应答时，可能会根据返回结果更新commit index。第二次RPC请求中，领导者会发送更新后的commit index给追随者，之后追随者会将这些日记条目标记为已提交并通过commit channel将它们发送给客户端。作为练习，请回到上面的示例代码中，找到这些步骤对应的片段。</p>
<h3 id="选举安全"><a href="#选举安全" class="headerlink" title="选举安全"></a>选举安全</h3><p>到目前为止，我们已经研究了为支持日志复制而添加的新代码。但是，日志也会对Raft选举产生影响。Raft论文中在5.4.1小节（<em>选举约束</em>）中进行了描述。除非候选人的日志与集群中多数同伴服务器一样新，否则Raft的选举程序会阻止其胜选<sup id="fnref:4"><a href="#fn:4" rel="footnote">4</a></sup>。</p>
<p>因此，RV请求中包含<code>lastLogIndex</code>和<code>lastLogTerm</code>字段。当候选人发送RV请求时，它会填入其最新日志条目的相关信息。追随者会与本身的属性进行对比，并决定该候选人是否有资格当选。</p>
<p>下面是最新的<code>startElection</code>代码：</p>
<pre class=" language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token punctuation">(</span>cm <span class="token operator">*</span>ConsensusModule<span class="token punctuation">)</span> <span class="token function">startElection</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  cm<span class="token punctuation">.</span>state <span class="token operator">=</span> Candidate
  cm<span class="token punctuation">.</span>currentTerm <span class="token operator">+=</span> <span class="token number">1</span>
  savedCurrentTerm <span class="token operator">:=</span> cm<span class="token punctuation">.</span>currentTerm
  cm<span class="token punctuation">.</span>electionResetEvent <span class="token operator">=</span> time<span class="token punctuation">.</span><span class="token function">Now</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  cm<span class="token punctuation">.</span>votedFor <span class="token operator">=</span> cm<span class="token punctuation">.</span>id
  cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"becomes Candidate (currentTerm=%d); log=%v"</span><span class="token punctuation">,</span> savedCurrentTerm<span class="token punctuation">,</span> cm<span class="token punctuation">.</span>log<span class="token punctuation">)</span>

  <span class="token keyword">var</span> votesReceived <span class="token builtin">int32</span> <span class="token operator">=</span> <span class="token number">1</span>

  <span class="token comment" spellcheck="true">// Send RequestVote RPCs to all other servers concurrently.</span>
  <span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> peerId <span class="token operator">:=</span> <span class="token keyword">range</span> cm<span class="token punctuation">.</span>peerIds <span class="token punctuation">{</span>
    <span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span>peerId <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment" spellcheck="true">/*---------以下代码为新增--------*/</span>
      cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      savedLastLogIndex<span class="token punctuation">,</span> savedLastLogTerm <span class="token operator">:=</span> cm<span class="token punctuation">.</span><span class="token function">lastLogIndexAndTerm</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

      args <span class="token operator">:=</span> RequestVoteArgs<span class="token punctuation">{</span>
        Term<span class="token punctuation">:</span>         savedCurrentTerm<span class="token punctuation">,</span>
        CandidateId<span class="token punctuation">:</span>  cm<span class="token punctuation">.</span>id<span class="token punctuation">,</span>
        LastLogIndex<span class="token punctuation">:</span> savedLastLogIndex<span class="token punctuation">,</span>
        LastLogTerm<span class="token punctuation">:</span>  savedLastLogTerm<span class="token punctuation">,</span>
      <span class="token punctuation">}</span>
      <span class="token comment" spellcheck="true">/*---------以上代码为新增--------*/</span>

      cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"sending RequestVote to %d: %+v"</span><span class="token punctuation">,</span> peerId<span class="token punctuation">,</span> args<span class="token punctuation">)</span>
      <span class="token keyword">var</span> reply RequestVoteReply
      <span class="token keyword">if</span> err <span class="token operator">:=</span> cm<span class="token punctuation">.</span>server<span class="token punctuation">.</span><span class="token function">Call</span><span class="token punctuation">(</span>peerId<span class="token punctuation">,</span> <span class="token string">"ConsensusModule.RequestVote"</span><span class="token punctuation">,</span> args<span class="token punctuation">,</span> <span class="token operator">&amp;</span>reply<span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
        cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token keyword">defer</span> cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"received RequestVoteReply %+v"</span><span class="token punctuation">,</span> reply<span class="token punctuation">)</span>

        <span class="token keyword">if</span> cm<span class="token punctuation">.</span>state <span class="token operator">!=</span> Candidate <span class="token punctuation">{</span>
          cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"while waiting for reply, state = %v"</span><span class="token punctuation">,</span> cm<span class="token punctuation">.</span>state<span class="token punctuation">)</span>
          <span class="token keyword">return</span>
        <span class="token punctuation">}</span>

        <span class="token keyword">if</span> reply<span class="token punctuation">.</span>Term <span class="token operator">></span> savedCurrentTerm <span class="token punctuation">{</span>
          cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"term out of date in RequestVoteReply"</span><span class="token punctuation">)</span>
          cm<span class="token punctuation">.</span><span class="token function">becomeFollower</span><span class="token punctuation">(</span>reply<span class="token punctuation">.</span>Term<span class="token punctuation">)</span>
          <span class="token keyword">return</span>
        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token keyword">if</span> reply<span class="token punctuation">.</span>Term <span class="token operator">==</span> savedCurrentTerm <span class="token punctuation">{</span>
          <span class="token keyword">if</span> reply<span class="token punctuation">.</span>VoteGranted <span class="token punctuation">{</span>
            votes <span class="token operator">:=</span> <span class="token function">int</span><span class="token punctuation">(</span>atomic<span class="token punctuation">.</span><span class="token function">AddInt32</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>votesReceived<span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
            <span class="token keyword">if</span> votes<span class="token operator">*</span><span class="token number">2</span> <span class="token operator">></span> <span class="token function">len</span><span class="token punctuation">(</span>cm<span class="token punctuation">.</span>peerIds<span class="token punctuation">)</span><span class="token operator">+</span><span class="token number">1</span> <span class="token punctuation">{</span>
              <span class="token comment" spellcheck="true">// Won the election!</span>
              cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"wins election with %d votes"</span><span class="token punctuation">,</span> votes<span class="token punctuation">)</span>
              cm<span class="token punctuation">.</span><span class="token function">startLeader</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
              <span class="token keyword">return</span>
            <span class="token punctuation">}</span>
          <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">(</span>peerId<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>

  <span class="token comment" spellcheck="true">// Run another election timer, in case this election is not successful.</span>
  <span class="token keyword">go</span> cm<span class="token punctuation">.</span><span class="token function">runElectionTimer</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span></code></pre>
<p>其中是<code>lastLogIndexAndTerm</code>是一个新的辅助方法：</p>
<pre class=" language-go"><code class="language-go"><span class="token comment" spellcheck="true">// lastLogIndexAndTerm方法返回服务器最新的日志索引及最新的日志条目对应的任期</span>
<span class="token comment" spellcheck="true">// （如果没有日志返回-1）要求cm.mu锁定</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>cm <span class="token operator">*</span>ConsensusModule<span class="token punctuation">)</span> <span class="token function">lastLogIndexAndTerm</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">(</span><span class="token builtin">int</span><span class="token punctuation">,</span> <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token function">len</span><span class="token punctuation">(</span>cm<span class="token punctuation">.</span>log<span class="token punctuation">)</span> <span class="token operator">></span> <span class="token number">0</span> <span class="token punctuation">{</span>
    lastIndex <span class="token operator">:=</span> <span class="token function">len</span><span class="token punctuation">(</span>cm<span class="token punctuation">.</span>log<span class="token punctuation">)</span> <span class="token operator">-</span> <span class="token number">1</span>
    <span class="token keyword">return</span> lastIndex<span class="token punctuation">,</span> cm<span class="token punctuation">.</span>log<span class="token punctuation">[</span>lastIndex<span class="token punctuation">]</span><span class="token punctuation">.</span>Term
  <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">1</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p>提醒一下，我们实现中的索引是从0开始的，而不像Raft论文中是从1开始的，因此-1经常作为一个标记值。</p>
<p>下面是更新后的RV处理逻辑，实现了选举安全性检查：</p>
<pre class=" language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token punctuation">(</span>cm <span class="token operator">*</span>ConsensusModule<span class="token punctuation">)</span> <span class="token function">RequestVote</span><span class="token punctuation">(</span>args RequestVoteArgs<span class="token punctuation">,</span> reply <span class="token operator">*</span>RequestVoteReply<span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">{</span>
  cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  <span class="token keyword">defer</span> cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  <span class="token keyword">if</span> cm<span class="token punctuation">.</span>state <span class="token operator">==</span> Dead <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token boolean">nil</span>
  <span class="token punctuation">}</span>
  lastLogIndex<span class="token punctuation">,</span> lastLogTerm <span class="token operator">:=</span> cm<span class="token punctuation">.</span><span class="token function">lastLogIndexAndTerm</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"RequestVote: %+v [currentTerm=%d, votedFor=%d, log index/term=(%d, %d)]"</span><span class="token punctuation">,</span> args<span class="token punctuation">,</span> cm<span class="token punctuation">.</span>currentTerm<span class="token punctuation">,</span> cm<span class="token punctuation">.</span>votedFor<span class="token punctuation">,</span> lastLogIndex<span class="token punctuation">,</span> lastLogTerm<span class="token punctuation">)</span>

  <span class="token keyword">if</span> args<span class="token punctuation">.</span>Term <span class="token operator">></span> cm<span class="token punctuation">.</span>currentTerm <span class="token punctuation">{</span>
    cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"... term out of date in RequestVote"</span><span class="token punctuation">)</span>
    cm<span class="token punctuation">.</span><span class="token function">becomeFollower</span><span class="token punctuation">(</span>args<span class="token punctuation">.</span>Term<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>

  <span class="token comment" spellcheck="true">// 任期相同，未投票或已投票给当前请求同伴，且候选人的日志满足安全性要求， 则返回赞成投票；</span>
  <span class="token comment" spellcheck="true">// 否则，返回反对投票。</span>
  <span class="token keyword">if</span> cm<span class="token punctuation">.</span>currentTerm <span class="token operator">==</span> args<span class="token punctuation">.</span>Term <span class="token operator">&amp;&amp;</span>
    <span class="token punctuation">(</span>cm<span class="token punctuation">.</span>votedFor <span class="token operator">==</span> <span class="token operator">-</span><span class="token number">1</span> <span class="token operator">||</span> cm<span class="token punctuation">.</span>votedFor <span class="token operator">==</span> args<span class="token punctuation">.</span>CandidateId<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span>
    <span class="token punctuation">(</span>args<span class="token punctuation">.</span>LastLogTerm <span class="token operator">></span> lastLogTerm <span class="token operator">||</span>
      <span class="token punctuation">(</span>args<span class="token punctuation">.</span>LastLogTerm <span class="token operator">==</span> lastLogTerm <span class="token operator">&amp;&amp;</span> args<span class="token punctuation">.</span>LastLogIndex <span class="token operator">>=</span> lastLogIndex<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    reply<span class="token punctuation">.</span>VoteGranted <span class="token operator">=</span> <span class="token boolean">true</span>
    cm<span class="token punctuation">.</span>votedFor <span class="token operator">=</span> args<span class="token punctuation">.</span>CandidateId
    cm<span class="token punctuation">.</span>electionResetEvent <span class="token operator">=</span> time<span class="token punctuation">.</span><span class="token function">Now</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
    reply<span class="token punctuation">.</span>VoteGranted <span class="token operator">=</span> <span class="token boolean">false</span>
  <span class="token punctuation">}</span>
  reply<span class="token punctuation">.</span>Term <span class="token operator">=</span> cm<span class="token punctuation">.</span>currentTerm
  cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"... RequestVote reply: %+v"</span><span class="token punctuation">,</span> reply<span class="token punctuation">)</span>
  <span class="token keyword">return</span> <span class="token boolean">nil</span>
<span class="token punctuation">}</span></code></pre>
<h3 id="回顾”服务器失控“场景"><a href="#回顾”服务器失控“场景" class="headerlink" title="回顾”服务器失控“场景"></a>回顾”服务器失控“场景</h3><p>在[第一部分](./实现Raft协议：Part 1 - 选主.md)中，我们讨论了一个场景。在具有三台服务器的集群中，服务器B断开连接几秒钟，导致其变为候选人并且每隔150-300ms就发起一轮选举。当它重新连入集群中时，其任期要比留在集群中不知道有新一轮选举的同伴服务器高很多。</p>
<p>现在正好可以回顾这个场景，并考虑一下，如果连接正常的同伴服务器在此期间复制了新的日志条目，将会发生什么。</p>
<p>虽然B重返集群时会引发重新选举（领导者会在AE的应答中看到更高的任期而转换为追随者），但是因为它的日志不如A和C完整，所以B不可能胜选。这就是因为上一节所说的选举安全性检查。A或C会赢得新一轮的选举，因此（这次选举）对集群的破坏力相对较小。</p>
<p>如果您仍然担心这个不必要的影响（为什么要改选？），Ongaro的论文在<code>Preventing disruptions when a server rejoins a cluster</code>一节讨论了这个确切的问题。这个问题的常用解决方案就是”预投票“，即服务器在成为候选人之前先执行一些检查。</p>
<p>因为这是真的非常规情形的优化，我就不在这个主题上花费太多时间。大家可以去查看论文——<a target="_blank" rel="noopener" href="https://raft.github.io/">Raft网站</a>提供了链接。</p>
<h3 id="Q-amp-A"><a href="#Q-amp-A" class="headerlink" title="Q&amp;A"></a>Q&amp;A</h3><p>结束本节之前，我们看一些在学习和实现Raft时常见的问题。如果你有其它问题，请随时给我发邮件——我会收集最常见的问题并更新文章。</p>
<p><strong>Q：</strong>为什么<code>commitIndex</code>和<code>lastApplied</code>是分开的？我们能不能只记录因为RPC请求（或RPC响应）导致<code>commitIndex</code>变化了多少，然后只将这些变化的指令发给客户端？</p>
<p><strong>A：</strong>这两者分开是为了将快速操作（RPC处理）与较慢的操作（向客户端发送命令）进行解耦。考虑一下，当追随者收到AE请求，发现领导者的<code>commitIndex</code>比自己大时，会发生什么？此时，它可以向commit channel发送一下日志指令。但是在channel发送数据（或执行回调函数）可能是一个潜在的阻塞操作，而我们希望尽可能快地应答RPC请求。<code>lastApplied</code>就可以帮助我们将二者进行解耦，RPC方法只需要更新<code>commitIndex</code>，后台的<code>commitChanSender</code>goroutine会观察这些变化，并在空闲时把新提交的指令发送给客户端。</p>
<p>那你可能会问对于<code>newCommitReadyChan</code>通道的操作是不是也存在这个问题？观察很仔细，但是通道是有缓冲的，而且由于通道两边都是我们控制的，我们可以设置一个小的缓冲区，来保证在绝大多数情况下不会阻塞。尽管如此，在极少数情况下，因为Raft代码中不可能提供无限的缓冲区，非常慢的客户端会拖延RPC请求。这未必是一件坏事，因为它会形成一种自然的背压机制。</p>
<p><strong>Q：</strong>我们在领导者中需要为每个同伴都保存<code>nextIndex</code>和<code>matchIndex</code>吗？</p>
<p><strong>A：</strong>只有<code>matchIndex</code>时算法也仍然是有效的，但是在有些情况下效率会很低。考虑一个领导改变的情况，新的领导者不能假设任何关于其同伴的最新情况，所以将<code>matchIndex</code>初始化为-1，因此就会尝试向每个追随者都发送整个日志。但是追随者（至少大部分）很可能拥有几乎相同的日志条目；<code>nextIndex</code>帮助领导者从<em>日志末尾</em>开始探查追随者（所需的日志），而不必复制大量的日志。</p>
<h3 id="下一步"><a href="#下一步" class="headerlink" title="下一步"></a>下一步</h3><p>我再一次强烈建议您研究一下<a target="_blank" rel="noopener" href="https://github.com/eliben/raft/tree/master/part2">代码</a>——运行测试用例，观察输出日志。</p>
<p>到目前为止，我们已经有了一个基本可以使用的Raft实现，除了还没有处理<em>持久性</em>。这意味着我们的实现难以应对崩溃故障，即服务器崩溃并重启。</p>
<p>Raft算法对此做了规定，这是<a href="/posts/9e1d4cec.html" title="第三部分">第三部分</a>将讨论的内容。增加持久性会使我们能够应对更严格的测试，包括最坏情况下的服务器崩溃。</p>
<p>此外，第三部分会讨论这里提到的一些优化。更重要的是，如果领导者有新消息要发送给追随者时，应该更及时地发送AE请求，但是现在领导者只会在每50ms发送一次AE。这个也会在下一部分被修正。</p>
<div id="footnotes"><hr><div id="footnotelist"><ol style="list-style:none; padding-left: 0;"><li id="fn:1"><span style="display: inline-block; vertical-align: top; padding-right: 10px;">1.</span><span style="display: inline-block; vertical-align: top;">举例来说，在规模为5的集群中，领导者期望得到2个追随者的确认回复，这样总数就是3个（2个追随者加领导者自身），也就满足了多数的要求。</span><a href="#fnref:1" rev="footnote"> ↩</a></li><li id="fn:2"><span style="display: inline-block; vertical-align: top; padding-right: 10px;">2.</span><span style="display: inline-block; vertical-align: top;">这里需要注意，虽然Raft论文中的日志索引是从1开始的，在我们的实现中索引是从0开始的，因为这样的代码感觉更自然。这些索引对于<code>ConsensusModule</code>的客户端/用户没有任何实质性影响。</span><a href="#fnref:2" rev="footnote"> ↩</a></li><li id="fn:3"><span style="display: inline-block; vertical-align: top; padding-right: 10px;">3.</span><span style="display: inline-block; vertical-align: top;">在这里将这个方法命名为<code>leaderSendHeartbeats</code>有点不恰当，因为它不只是发送心跳。但是，因为在这一部分中，该方法每隔50ms都需要发送AE请求，所以保留了这个名字。在第三部分中我们会修正。</span><a href="#fnref:3" rev="footnote"> ↩</a></li><li id="fn:4"><span style="display: inline-block; vertical-align: top; padding-right: 10px;">4.</span><span style="display: inline-block; vertical-align: top;">这里用了一个非常简单的解释，实际情况很复杂。这里对于正确性的推理相当复杂，我建议阅读论文以获取更多详细信息。如果你是形式主义的拥趸，Ongaro的毕业论文有章节<a target="_blank" rel="noopener" href="https://github.com/ongardie/raft.tla">TLA+ spec of Raft</a>来证明这些不变式的正确性。</span><a href="#fnref:4" rev="footnote"> ↩</a></li></ol></div></div>
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Guo Yaxiang</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.codinghonest.space/posts/25bc8c4b.html">https://www.codinghonest.space/posts/25bc8c4b.html</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Guo Yaxiang</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E4%B8%80%E8%87%B4%E6%80%A7/">
                                    <span class="chip bg-color">分布式一致性</span>
                                </a>
                            
                                <a href="/tags/Raft/">
                                    <span class="chip bg-color">Raft</span>
                                </a>
                            
                                <a href="/tags/%E8%AF%91%E6%96%87/">
                                    <span class="chip bg-color">译文</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    
        <style>
    .mvaline-card {
        margin: 1.5rem auto;
    }

    .mvaline-card .card-content {
        padding: 20px 20px 5px 20px;
    }
</style>

<div class="card mvaline-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="mvcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/minivaline/MiniValine.js"></script>
<script>
    new MiniValine({
        el: '#mvcomments',
        appId: 'oqAo7rCWejwTqHjGC2APTVDX-MdYXbMMI',
        appKey: 'pfyY919tO7iJaDm7lFmvh5Wp',
        mode: 'DesertsP',
        placeholder: 'Write a Comment',
        pathname: window.location.pathname,
        lang: '',
        adminEmailMd5: '8BBC105436DAAF8C803841C8FD13CD0C',
        tagMeta: ["管理员", "小伙伴", "访客"],
        master: ["8BBC105436DAAF8C803841C8FD13CD0C"],
        friends: ["FA21C7921CD42FE9523E957870873F64", "586BAB41BB5692877F7714DFE4947DEC"],
        math: true,
        md: true,
        enableQQ: false,
        NoRecordIP: false,
        visitor: true,
        maxNest: 6,
        pageSize: 6,
        serverURLs: '',
        emoticonUrl: ["https://cdn.jsdelivr.net/npm/alus@latest", "https://cdn.jsdelivr.net/gh/MiniValine/qq@latest", "https://cdn.jsdelivr.net/gh/MiniValine/Bilibilis@latest", "https://cdn.jsdelivr.net/gh/MiniValine/tieba@latest", "https://cdn.jsdelivr.net/gh/MiniValine/twemoji@latest", "https://cdn.jsdelivr.net/gh/MiniValine/weibo@latest"],
    });
</script>

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/posts/9e1d4cec.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/0.jpg" class="responsive-img" alt="实现Raft协议：Part 3 - 持久性和优化">
                        
                        <span class="card-title">实现Raft协议：Part 3 - 持久性和优化</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本系列文章的写作目的，在于描述Raft协议的一个功能完备且经过严格测试的实现方式，并提供一些Raft工作方式的直观理解。
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-03-04
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F/" class="post-category">
                                    分布式
                                </a>
                            
                            <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F/%E4%B8%80%E8%87%B4%E6%80%A7%E5%8D%8F%E8%AE%AE/" class="post-category">
                                    一致性协议
                                </a>
                            
                            <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F/%E4%B8%80%E8%87%B4%E6%80%A7%E5%8D%8F%E8%AE%AE/Raft/" class="post-category">
                                    Raft
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E4%B8%80%E8%87%B4%E6%80%A7/">
                        <span class="chip bg-color">分布式一致性</span>
                    </a>
                    
                    <a href="/tags/Raft/">
                        <span class="chip bg-color">Raft</span>
                    </a>
                    
                    <a href="/tags/%E8%AF%91%E6%96%87/">
                        <span class="chip bg-color">译文</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/posts/be586517.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/21.jpg" class="responsive-img" alt="实现Raft协议：Part 1 - 选主">
                        
                        <span class="card-title">实现Raft协议：Part 1 - 选主</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本系列文章的写作目的，在于描述Raft协议的一个功能完备且经过严格测试的实现方式，并提供一些Raft工作方式的直观理解。
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-03-04
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F/" class="post-category">
                                    分布式
                                </a>
                            
                            <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F/%E4%B8%80%E8%87%B4%E6%80%A7%E5%8D%8F%E8%AE%AE/" class="post-category">
                                    一致性协议
                                </a>
                            
                            <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F/%E4%B8%80%E8%87%B4%E6%80%A7%E5%8D%8F%E8%AE%AE/Raft/" class="post-category">
                                    Raft
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E4%B8%80%E8%87%B4%E6%80%A7/">
                        <span class="chip bg-color">分布式一致性</span>
                    </a>
                    
                    <a href="/tags/Raft/">
                        <span class="chip bg-color">Raft</span>
                    </a>
                    
                    <a href="/tags/%E8%AF%91%E6%96%87/">
                        <span class="chip bg-color">译文</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 码道诚公<br />'
            + '文章作者: Guo Yaxiang<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2020-2021</span>
            
            <span id="year">2020</span>
            <a href="/about" target="_blank">Guo Yaxiang</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
            
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link ">
    <a href="https://github.com/GuoYaxiang" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:YXGyxg112358@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1431800679" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1431800679" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/guo-ya-xiang" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/guo-ya-xiang" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    

    
        <script src="//code.tidio.co/zgiqinzrat1rzwxseqhr2pnzsp2a4rjo.js"></script>
        <script>
            $(document).ready(function () {
                setInterval(change_Tidio, 50);
                function change_Tidio() {
                    var tidio=$("#tidio-chat iframe");
                    if(tidio.css("display")=="block"&& $(window).width()>977 ){
                        document.getElementById("tidio-chat-iframe").style.bottom= ($("div#backTop.top-scroll").css("display")=="none" &&$(window).width()>977)>0? "-40px" : ($("div.toc-title").length&&$(window).width()>977)>0?"85px":"20px";
                        document.getElementById("tidio-chat-iframe").style.right="-15px";
                        document.getElementById("tidio-chat-iframe").style.height=parseInt(tidio.css("height"))>=520?"520px":tidio.css("height");
                        document.getElementById("tidio-chat-iframe").style.zIndex="997";
                    }
                    else if(tidio.css("display")=="block"&&$(window).width()>601 &&$(window).width()<992 ){
                        document.getElementById("tidio-chat-iframe").style.bottom= ($("div#backTop.top-scroll").css("display")=="none" && 601< $(window).width()<992)>0? "-40px":"20px" ;
                        document.getElementById("tidio-chat-iframe").style.right="-15px";
                        document.getElementById("tidio-chat-iframe").style.zIndex="997";
                    }
                    else if(tidio.css("display")=="block"&&$(window).width()<601 && parseInt(tidio.css("height"))<230){
                        document.getElementById("tidio-chat-iframe").style.bottom= ($("div#backTop.top-scroll").css("display")=="none" && $(window).width()<601)>0? "-10px":"45px" ;
                        document.getElementById("tidio-chat-iframe").style.zIndex="997";
                    }
                    if( tidio.css("display")=="block"&&$(window).width()<601 && parseInt(tidio.css("height"))>=230){
                        document.getElementById("tidio-chat-iframe").style.zIndex="998";
                    }
                }
            });
        </script>
    

    

    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
